package initialize

import (
	"fmt"
	_ "github.com/mbobakov/grpc-consul-resolver" // It's important
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	"mxshop_api/user-web/global"
	"mxshop_api/user-web/proto"
)

func InitSrvConn() {
	consulInfo := global.ServerConfig.ConsulInfo
	userConn, err := grpc.NewClient(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s", consulInfo.Host, consulInfo.Port, global.ServerConfig.UserSrvInfo.Name),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
	)
	if err != nil {
		zap.S().Fatalf("[InifSrvConn] 连接 【用户服务】失败")
	}
	userSrvClient := proto.NewUserClient(userConn)
	global.UserSrvClient = userSrvClient
}

/*
func InitSrvConn2() {
	// 从注册中心获取用户服务信息
	cfg := api.DefaultConfig()
	consulInfo := global.ServerConfig.ConsulInfo
	cfg.Address = fmt.Sprintf("%s:%d", consulInfo.Host, consulInfo.Port)
	userSrvHost := ""
	userSrvPort := 0
	client, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
	}
	sprintf := fmt.Sprintf(`Service == "%s"`, global.ServerConfig.UserSrvInfo.Name)
	data, err := client.Agent().ServicesWithFilter(sprintf)

	if err != nil {
		panic(err)
	}
	for _, value := range data {
		userSrvHost = value.Address
		userSrvPort = value.Port
		break
	}
	if userSrvHost == "" {
		zap.S().Fatal("[InitSrvConn] 连接 【用户服务】失败")
		return
	}
	// 连接用户服务   grpc.WithTransportCredentials(insecure.NewCredentials())
	//userConn, err := grpc.Dial(fmt.Sprintf("%s:%d", userSrvHost, userSrvPort), grpc.WithInsecure())
	userConn, err := grpc.NewClient(fmt.Sprintf("%s:%d", userSrvHost, userSrvPort), grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		zap.S().Errorf("[GetUserList]连接 【用户服务失败】",
			"msg", err.Error(),
		)
	}

	// 1、后续的用户服务下线了 2、该端口了 3、该ip了 负载均衡来做
	// 2、已经事先创立了连接，这样后续就不用再次进行tcp的三次握手了
	// 3、 一个连接多个groutine公用，会产生性能问题，所以这里可以使用连接池技术来优化
	userSrvClient := proto.NewUserClient(userConn)
	global.UserSrvClient = userSrvClient
}*/
